package course.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import course.pojo.entity.College;
import course.pojo.entity.Zhuanye;
import course.pojo.vo.Page;
import course.pojo.vo.ZhuanyeRespVo;
import course.service.CollegeService;
import course.service.ZhuanyeService;
import course.service.impl.CollegeServiceImpl;
import course.service.impl.ZhuanyeServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/1 20:17
 */
@WebServlet("/admin/zhuanyeController")
public class ZhuanyeController extends BaseController {
    private ZhuanyeService zhuanyeService = new ZhuanyeServiceImpl();

    private CollegeService collegeService = new CollegeServiceImpl();

    protected void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNo = req.getParameter("pageNo");
        this.main(req, resp, pageNo);
    }

    protected void main(HttpServletRequest req, HttpServletResponse resp, String pageNo) throws ServletException, IOException {
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<Zhuanye> page = zhuanyeService.page(Integer.valueOf(pageNo));
        List<Zhuanye> zhuanyeList = page.getList();
        List<ZhuanyeRespVo> respVos = zhuanyeList.stream().map(zhuanye -> {
            try {
                ZhuanyeRespVo respVo = new ZhuanyeRespVo();
                BeanUtils.copyProperties(respVo, zhuanye);
                String cname = collegeService.getById(zhuanye.getCid()).getCname();
                respVo.setCname(cname);

                return respVo;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        Page<ZhuanyeRespVo> voPage = new Page<>();
        try {
            //将zhuanye的page对象属性对拷到zhuanyeRespVo中
            BeanUtils.copyProperties(voPage, page);
            voPage.setList(respVos);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        req.setAttribute("page", voPage);
        req.getRequestDispatcher("/zhuanye_manage.jsp").forward(req, resp);
    }

    /**
     * 添加专业
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String zname = req.getParameter("zname");
        String zdesc = req.getParameter("zdesc");
        String cid = req.getParameter("cid");

        String total = req.getParameter("total");
        String pages = req.getParameter("pages");


        Integer pageSize = new Page<>().getPageSize();

        Integer pages2 = Integer.valueOf(pages);
        if (Integer.parseInt(total) % pageSize == 0) {
            pages2 += 1;
        }

        Zhuanye zhuanye = new Zhuanye(null, zname, zdesc, Integer.valueOf(cid));
        int i = zhuanyeService.addZhuanye(zhuanye);
        if (i > 0) {
            this.main(req, resp, String.valueOf(pages2));
        }
    }

    /**
     * 删除专业
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String zid = req.getParameter("zid");
        String pn = req.getParameter("pn");

        int i = zhuanyeService.deleteById(Integer.valueOf(zid));
        if (i > 0) {
            this.main(req, resp, pn);
        }
    }

    /**
     * 批量删除所有选中专业
     */
    protected void deleteSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids[]");

        List<String> list = Arrays.asList(ids);
        List<Integer> integers = list.stream().map(Integer::valueOf).collect(Collectors.toList());

        int i = zhuanyeService.deleteSelect(integers);
        if (i > 0) {
            this.index(req, resp);
        }
    }

    /**
     * 通过zid获取zhuanye对象
     */
    protected void getZhuanye(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String zid = req.getParameter("zid");

        Zhuanye zhuanye = zhuanyeService.getById(Integer.valueOf(zid));
        ObjectMapper mapper = new ObjectMapper();

        College college = collegeService.getById(zhuanye.getCid());
        ZhuanyeRespVo zhuanyeRespVo = new ZhuanyeRespVo();
        try {
            BeanUtils.copyProperties(zhuanyeRespVo, zhuanye);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        zhuanyeRespVo.setCname(college.getCname());

        String jsonString = mapper.writeValueAsString(zhuanyeRespVo);
        PrintWriter writer = resp.getWriter();
        writer.write(jsonString); //将json对象响应给前端
        writer.flush();
    }

    /**
     * 修改专业
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String zid = req.getParameter("zid");
        String zname = req.getParameter("zname");
        String pzname = req.getParameter("pzname");
        String zdesc = req.getParameter("zdesc");
        String cid = req.getParameter("cid");
        String pn = req.getParameter("pn");


        Zhuanye zhuanye = new Zhuanye(Integer.valueOf(zid), zname, zdesc, Integer.valueOf(cid));

        int i = zhuanyeService.updateById(zhuanye);
        if (i > 0) {
            this.main(req, resp, pn);
        }
    }

    /**
     * 查询所有课程数量
     */
    protected void count(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        long count = zhuanyeService.count();
        PrintWriter writer = resp.getWriter();
        writer.println(count);
        writer.flush();
    }

    /**
     * 根据课程名查询课程信息
     */
    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String zname = req.getParameter("zname");

        String pageNo = req.getParameter("pageNo");
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<Zhuanye> page = zhuanyeService.query(zname, Integer.valueOf(pageNo));

        List<Zhuanye> zhuanyeList = page.getList();
        List<ZhuanyeRespVo> respVos = zhuanyeList.stream().map(zhuanye -> {
            try {
                ZhuanyeRespVo respVo = new ZhuanyeRespVo();
                BeanUtils.copyProperties(respVo, zhuanye);
                String cname = collegeService.getById(zhuanye.getCid()).getCname();
                respVo.setCname(cname);

                return respVo;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        Page<ZhuanyeRespVo> voPage = new Page<>();
        try {
            //将zhuanye的page对象属性对拷到zhuanyeRespVo中
            BeanUtils.copyProperties(voPage, page);
            voPage.setList(respVos);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        req.setAttribute("zname",zname);
        req.setAttribute("page", voPage);
        req.getRequestDispatcher("/zhuanye_manage.jsp").forward(req, resp);
    }

    /**
     * 通过专业名判断该专业是否存在
     */
    protected void exit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String zname = req.getParameter("zname");

        if (StringUtils.isBlank(zname)) {
            result.put("code", 0);
            result.put("msg", "专业不能为空！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }

        Zhuanye byZname = zhuanyeService.getByZname(zname);
        if (byZname != null) {
            result.put("code", 0);
            result.put("msg", "该专业已经存在！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }
        result.put("code", 1);
        result.put("msg", "该专业不存在，可以新增");
        writer.println(mapper.writeValueAsString(result));
    }

    /**
     * 通过专业名判断该专业是否存在2
     */
    protected void exit2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        //响应给前端的code,msg
        Map<String, Object> result = new HashMap<>();

        String zname = req.getParameter("zname");
        String pzname = req.getParameter("pzname");

        if (StringUtils.isBlank(zname)) {
            result.put("code", 0);
            result.put("msg", "专业不能为空！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }

        Zhuanye byZname = zhuanyeService.getByZname(zname);
        if (byZname != null && !byZname.getZname().equals(pzname)) {
            result.put("code", 0);
            result.put("msg", "该专业已经存在！");
            writer.println(mapper.writeValueAsString(result));
            return;
        }
        result.put("code", 1);
        result.put("msg", "该专业不存在，可以新增");
        writer.println(mapper.writeValueAsString(result));
    }
}
